package com.tim.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.OfficialNotice;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.OfficialNoticeListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.adapter.message.OfficialNoticeAdapter;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 官方通知页面
 */
public class OfficialNoticeActivity extends BaseActivity implements PtrHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "OfficialNoticeActivity";

    private ImageButton ibBack;

    private PtrClassicFrameLayout refresh_layout;
    private WrapRecyclerView wrvOfficicalNotice;

    private OfficialNoticeAdapter adapter;
    private List<OfficialNotice> dataList;

    private EmptyLayout emptyLayout;
    LinearLayoutManager layoutManager;

    private int pageNum = 1;

    private boolean isFromPush = false;

    public static void start(Context context, boolean isFromPush) {
        Intent intent = new Intent(context, OfficialNoticeActivity.class);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_officical_notice;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        refresh_layout = (PtrClassicFrameLayout) findViewById(R.id.refresh_layout);
        wrvOfficicalNotice = (WrapRecyclerView) findViewById(R.id.wrvOfficicalNotice);
        wrvOfficicalNotice.setOverScrollMode(View.OVER_SCROLL_NEVER);

        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibBack.setOnClickListener(this);

        refresh_layout.disableWhenHorizontalMove(true);
        refresh_layout.setPtrHandler(this);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvOfficicalNotice.setLayoutManager(layoutManager);

        dataList = new ArrayList<>();
        adapter = new OfficialNoticeAdapter(this, dataList);
        wrvOfficicalNotice.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

        emptyLayout = new EmptyLayout(this, refresh_layout);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_notice);
        emptyLayout.setEmptyText("还没有官方通知", "");
        emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.showLoading();
            }
        });
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);
    }

    @Override
    public void initData() {
        API_Found.ins().getOffiaiaPush(TAG, pageNum, AppKey.PAGE_SIZE, refreshCallback);
        UserManager.ins().updateUnreadOfficialMessageCount(0);
        EventManager.ins().sendEvent(EventTag.ON_OFFICIAL_UNREAD_MESSAGE_CHANGED, 0, 0, null);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                OfficialNoticeListResult result = new Gson().fromJson(resultValue, OfficialNoticeListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                            moveToPosition(dataList.size() - 1);
                        }
                        pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback loadHistoryCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                OfficialNoticeListResult result = new Gson().fromJson(resultValue, OfficialNoticeListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            pageNum = result.getRes().getArraylist().getCurrentPageNo();
                            dataList.addAll(0, result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.showToast("没有通知了");
                        }
                    }
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            wrvOfficicalNotice.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = wrvOfficicalNotice.getChildAt(n - firstItem).getTop();
            wrvOfficicalNotice.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            wrvOfficicalNotice.scrollToPosition(n);
        }
    }


    @Override
    public void onItemClick(View view, int position, long id) {
        OfficialNotice officialNotice = dataList.get(position);
        if (officialNotice.getOpenType() == 2 || officialNotice.getOpenType() == 3) {
            ViewGT.processNotice(this, officialNotice.getType(), officialNotice.getTypeId(), officialNotice.getOpenType(), officialNotice.getUrl(), false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
        }
    }


    @Override
    public void onBackPressed() {
        if (isFromPush) {
            ViewGT.gotoMainActivity(OfficialNoticeActivity.this);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvOfficicalNotice, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        API_Found.ins().getOffiaiaPush(TAG, pageNum + 1, AppKey.PAGE_SIZE, loadHistoryCallback);
    }

}
